package com.gp.exception;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.dao.DataAccessException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author: 弓成龙
 * @date : 2017年12月10日
 * @email : gcx909109@sina.cn
 * @description: 全局异常处理器
 */
public class CustomExceptionResolver implements HandlerExceptionResolver {
  /**
   * 系统抛出的异常
   */
  @Override
  public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) {
    CustomException customException = null;
    if (ex instanceof CustomException) {
      customException = (CustomException) ex;
    } else if (ex instanceof SQLException || ex instanceof DataAccessException) {
      customException = new CustomException("数据库异常");
    }else if (ex instanceof IllegalArgumentException ) {
      customException = new CustomException("非法的参数异常");
    }  else {
      // 如果该异常类型不是系统自定义的异常，构造一个自定义的异常类型（信息为“未知错误”）
      customException = new CustomException("未知错误");
    }
    // 错误信息
    String message = customException.getMessage();
    // 定义modelAndView
    ModelAndView modelAndView = new ModelAndView();
    // 将错误信息传到错误处理器
    request.setAttribute("detail", ex.getMessage());
    request.setAttribute("message", message);
    modelAndView.setViewName("/error");
    return modelAndView;
  }
}

